<script setup>
import { ref, onMounted, getCurrentInstance } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getList, deleteModel } from "../api/list";
// import printData from "./print/printData";
import printPreview from "./print/preview.vue";
import { newHiprintPrintTemplate } from "./print/template-helper";
import { provider1 } from "./print/provider1";
import { provider2 } from "./print/provider2";
// 二维码
import { useQrcodeStore } from "../stores/qrcode"
const qrcideStore = useQrcodeStore()
// import {getQrcode} from "../api/fis"
const router = useRouter();
const route = useRoute();
// console.log("router", route.query.invoiceParts);
import { useDispatchlistStore } from '../stores/dispatchList'
const dispatchlistStore = useDispatchlistStore()
let printData = {
  table: dispatchlistStore.invoiceParts,
  printTime: route.query.data,

  qrcode: dispatchlistStore.uuid,
}
onMounted(() => {
  // qrcideStore.funGetQrcode(dispatchlistStore.uuid)
  // console.log("printData", qrcideStore.qrcodeData);
});
const preView = ref(null);
const TEMPLATE_KEY = getCurrentInstance().type.name;
const fetchData = async () => {
  try {
    const response = await getList();
    dataSource.value = response.data;
  } catch (err) {
    console.error("Error fetching data:", err);
  }
};
const buildDesigner = () => {
  // $("#hiprint-printTemplate").empty(); // 先清空, 避免重复构建
  hiprintTemplate = newHiprintPrintTemplate(TEMPLATE_KEY, {
    template: templateRef.value, // 模板
    settingContainer: "#PrintElementOptionSetting", // 元素参数容器
  });
  // 构建 并填充到 容器中
  // hiprintTemplate.design("#hiprint-printTemplate");
};
onMounted(() => {
  fetchData();
  // test()
});
const dataSource = ref([
  {
    id: 18,
    title: "模板1",
    isDefault: "1",
    modelStr:
      '{"panels":[{"index":0,"name":1,"height":297,"width":210,"paperHeader":49.5,"paperFooter":780,"printElements":[{"options":{"left":192,"top":112.5,"height":16,"width":198,"testData":"单据类型","fontSize":15,"fontWeight":"700","textAlign":"center","title":"单据类型","right":390,"bottom":128.5,"vCenter":291,"hCenter":120.5,"field":"leixing","coordinateSync":false,"widthHeightSync":false,"qrCodeLevel":0},"printElementType":{"title":"单据类型","type":"text"}}],"paperNumberLeft":565.5,"paperNumberTop":819,"paperNumberContinue":true,"watermarkOptions":{},"panelLayoutOptions":{}}]}',
    createTime: "2025-03-11 13:46:09",
  },
]);
const getDimensions = (modelStr) => {
  try {
    const data = JSON.parse(modelStr);
    const panel = data.panels[0];
    return {
      width: panel.width,
      height: panel.height,
    };
  } catch (error) {
    return {
      width: "-",
      height: "-",
    };
  }
};
let hiprintTemplate;
const handleEdit = (scope) => {
  router.push({
    path: "/about",
    query: {
      data: JSON.stringify(scope.row),
    },
  });
};
const handleadd = () => {
  router.push({
    path: "/about",
  });
};
const handleDelete = (scope) => {
  deleteModel(scope.row.id).then((res) => {
    fetchData();
  });
  console.log(scope);
};
const templateRef = ref();
const handlePrint = (scope) => {
  const json = JSON.parse(scope.row.modelStr);
  templateRef.value = json;
  buildDesigner();
  let options = { leftOffset: -1, topOffset: -1 };
  // 扩展
  let ext = {
    callback: () => {
      console.log("浏览器打印窗口已打开");
    },
    styleHandler: () => {
      // 重写 文本 打印样式
      return "<style>.hiprint-printElement-text{color:red !important;}</style>";
    },
  };
  // 调用浏览器打印
  hiprintTemplate.print(printData, options, ext);
};
const handlePreview = (scope) => {

  const json = JSON.parse(scope.row.modelStr);
  templateRef.value = json;
  buildDesigner();
  preView.value.show(hiprintTemplate, printData, json.panels[0].width);
};
</script>
<template>
  <!-- 打印设计页面 -->
  <div class="home">
    <!-- 操作按钮区域 -->
    <div>
      <el-button @click="handleadd" type="primary">新增</el-button>
    </div>
    <el-table :data="dataSource" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column property="title" label="模板名称" width="200" />
      <el-table-column label="纸张大小" property="modelStr" width="120">
        <template #default="scope">
          {{
            getDimensions(scope.row.modelStr).width +
            " * " +
            getDimensions(scope.row.modelStr).height
          }}</template>
      </el-table-column>
      <el-table-column label="默认" property="isDefault" width="120">
        <template #default="scope">
          {{ scope.row.isDefault == "1" ? "是" : "否" }}</template>
      </el-table-column>
      <el-table-column label="创建时间" property="createTime" width="220">
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">
            设计
          </el-button>
          <el-button type="primary" size="small" @click="handlePrint(scope)">
            打印
          </el-button>
          <el-button type="primary" size="small" @click="handlePreview(scope)">
            预览
          </el-button>
          <!-- <el-button size="small" @click="handleUpdate(scope)">{{
              scope.row.isDefault == "1" ? "取消默认" : "设为默认"
            }}</el-button> -->
          <el-button size="small" @click="handleDelete(scope)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div id="PrintElementOptionSetting"></div>
  <print-preview ref="preView" />
</template>
<style scoped></style>